import {
  Controller,
  Post,
  UploadedFile,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { join, parse } from 'path';

import { simpleUUIDGenerator } from 'src/utils';

@Controller('admin/upload')
export class UploadController {
  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: join(__dirname, '../../../static/admin'), //存储在根目录的static文件夹下
        filename: (req, file, cb) => {
          const fileName: string = simpleUUIDGenerator(); //添加随机uuid
          const extension: string = parse(file.originalname).ext;
          cb(null, `${fileName}${extension}`);
        },
      }),
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File) {
    return {
      name: file.filename,
      path: 'admin/' + file.filename,
    };
  }

  @Post('uploadMultiple')
  @UseInterceptors(
    FilesInterceptor('files', 10, {
      storage: diskStorage({
        destination: join(__dirname, '../../../static/admin'),
        filename: (req, file, cb) => {
          const fileName: string = simpleUUIDGenerator(); //添加随机uuid
          const extension: string = parse(file.originalname).ext;
          cb(null, `${fileName}${extension}`);
        },
      }),
    }),
  )
  uploadMultipleFiles(@UploadedFiles() files: Express.Multer.File[]) {
    const response = [];
    files.forEach((file) => {
      const fileReponse = {
        name: file.filename,
        path: 'admin/' + file.filename,
      };
      response.push(fileReponse);
    });

    return response;
  }
}
